package cn.wsn2018.tools.service;

import cn.wsn2018.tools.common.CommonValue;
import cn.wsn2018.tools.util.JsonUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.Map;

/**
 * 类名称:IDCOdeService
 * 类描述:TODO
 * 创建人:nzx
 * 创建时间:2019/8/6 16:15
 */
@Service
public class IDCodeService {
    private static final Logger logger = LoggerFactory.getLogger(IDCodeService.class);
    /**
     * 生成验证码
     * @param request
     * @return
     */
    public String makeIDCode(HttpServletRequest request){
        HttpSession session = request.getSession(true);
        String IDCode = "";
        char[] randomArray = {'1','2','3','4','5','6','7','8','9','A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R', 'S','T','U','V','W','X','Y','Z'};
        for(int i = 0; i < 4; i++){
            //设置随机数范围,这设置为0 ~ 36
            int index = (int)Math.floor(Math.random()*35);
            //字符串拼接 将每次随机的字符 进行拼接
            IDCode += randomArray[index];
        }
        session.setAttribute("IDCode",IDCode);
        Map codeMap = new HashMap();
        codeMap.put("IDCode",IDCode);
        JSONObject jsonObject = JSONObject.fromObject(codeMap);
        return JsonUtil.successJson(CommonValue.JSON_IDCODE_SUCCESS,jsonObject,null);
    }

    /**
     * 校验验证码
     * @param code
     * @param request
     * @return
     */
    public String checkIDCode(String code,HttpServletRequest request){
        HttpSession session = request.getSession(true);
        String IDCode = session.getAttribute("IDCode").toString();
        if(code!=null&&!"".equals(code)){
            if(code.equals(IDCode)){
                return JsonUtil.successJson(CommonValue.JSON_CHECKIDCODE_SUCCESS,null,null);
            }else {

                return JsonUtil.failedJson(CommonValue.JSON_CHECKIDCODE_FAILED);
            }
        }else {
            return JsonUtil.failedJson(CommonValue.JSON_CHECKIDCODE_FAILED);
        }
    }

}
